<template>
  <a-layout style="min-height: 100vh; background: #f5f7fa;">
    <nav-bar />
    
    <a-layout-content style="padding: 30px 50px; max-width: 1400px; margin: 0 auto; width: 100%;">
      <!-- 页面标题 -->
      <div style="text-align: center; margin-bottom: 24px;">
        <h1 style="font-size: 28px; color: #2c3e50; font-weight: 600;">
          🧬 {{ $t('sequenceSearch.pageTitle') }}
        </h1>
        <p style="color: #606266;">{{ $t('sequenceSearch.pageSubtitle') }}</p>
      </div>
      
      <!-- 输入区域 -->
      <a-card style="margin-bottom: 16px; border-radius: 8px; border: 1px solid #e4e7ed;">
        <a-form layout="vertical">
          <a-form-item 
            :label="$t('sequenceSearch.inputLabel')" 
            :help="$t('sequenceSearch.inputHelp')"
          >
            <a-textarea
              v-model:value="querySequence"
              :rows="8"
              :placeholder="$t('sequenceSearch.inputPlaceholder')"
              :maxlength="11000"
              show-count
              style="font-family: 'Courier New', monospace;"
            />
          </a-form-item>
          
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item :label="$t('sequenceSearch.evalueLabel')" :help="$t('sequenceSearch.evalueHelp')">
                <a-input-number
                  v-model:value="evalue"
                  :min="0.00001"
                  :max="10"
                  :step="0.001"
                  style="width: 100%;"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('sequenceSearch.maxResultsLabel')" :help="$t('sequenceSearch.maxResultsHelp')">
                <a-input-number
                  v-model:value="maxResults"
                  :min="10"
                  :max="500"
                  :step="10"
                  style="width: 100%;"
                />
              </a-form-item>
            </a-col>
          </a-row>
          
          <a-form-item>
            <a-space>
              <a-button 
                type="primary" 
                size="large" 
                @click="searchSequence" 
                :loading="searching"
                :disabled="!querySequence.trim()"
              >
                <template #icon><search-outlined /></template>
                {{ $t('sequenceSearch.searchButton') }}
              </a-button>
              <a-button size="large" @click="clearForm">
                {{ $t('sequenceSearch.clearButton') }}
              </a-button>
              <a-button size="large" @click="loadExample">
                {{ $t('sequenceSearch.exampleButton') }}
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
      
      <!-- 搜索结果 -->
      <a-card 
        v-if="searchResults" 
        style="border-radius: 8px; border: 1px solid #e4e7ed;"
      >
        <template #title>
          <span style="font-size: 18px; color: #2c3e50; font-weight: 600;">
            {{ $t('sequenceSearch.resultsTitle') }}
            <a-tag v-if="searchResults.cached" color="blue" style="margin-left: 8px;">
              <template #icon><thunderbolt-outlined /></template>
              {{ $t('sequenceSearch.cached') }}
            </a-tag>
          </span>
        </template>
        
        <!-- 统计信息 -->
        <a-row :gutter="16" style="margin-bottom: 16px;">
          <a-col :span="6">
            <a-statistic 
              :title="$t('sequenceSearch.queryLength')" 
              :value="searchResults.query_length" 
              suffix="aa"
            >
              <template #prefix>
                <experiment-outlined style="color: #1890ff;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              :title="$t('sequenceSearch.totalHits')" 
              :value="searchResults.total_hits"
            >
              <template #prefix>
                <check-circle-outlined style="color: #52c41a;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              v-if="searchResults.execution_time"
              :title="$t('sequenceSearch.executionTime')" 
              :value="searchResults.execution_time.toFixed(3)" 
              :suffix="$t('common.seconds') || '秒'"
            >
              <template #prefix>
                <clock-circle-outlined style="color: #faad14;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              :title="$t('sequenceSearch.cacheStatus')" 
              :value="searchResults.cached ? $t('sequenceSearch.cacheHit') : $t('sequenceSearch.cacheMiss')"
            >
              <template #prefix>
                <database-outlined :style="{ color: searchResults.cached ? '#52c41a' : '#d9d9d9' }" />
              </template>
            </a-statistic>
          </a-col>
        </a-row>
        
        <!-- 结果表格 -->
        <a-table
          :dataSource="searchResults.results"
          :columns="columns"
          :pagination="{ pageSize: 20, showSizeChanger: true, showQuickJumper: true }"
          rowKey="accession"
          :scroll="{ x: 1200 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'accession'">
              <router-link :to="`/protein/${record.id}`">
                <a-typography-text copyable style="color: #1890ff;">
                  {{ record.accession }}
                </a-typography-text>
              </router-link>
            </template>
            
            <template v-else-if="column.key === 'species'">
              <a-tooltip :title="record.species">
                <span style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; display: block;">
                  {{ record.species }}
                </span>
              </a-tooltip>
            </template>
            
            <template v-else-if="column.key === 'identity'">
              <a-progress
                :percent="record.identity"
                :format="percent => `${percent.toFixed(1)}%`"
                :strokeColor="getIdentityColor(record.identity)"
                :showInfo="true"
                style="width: 150px;"
              />
            </template>
            
            <template v-else-if="column.key === 'evalue'">
              <span :style="{ 
                color: record.evalue < 1e-50 ? '#52c41a' : record.evalue < 1e-10 ? '#1890ff' : '#606266',
                fontFamily: 'monospace'
              }">
                {{ record.evalue.toExponential(2) }}
              </span>
            </template>
            
            <template v-else-if="column.key === 'bit_score'">
              <span style="font-family: monospace;">
                {{ record.bit_score.toFixed(1) }}
              </span>
            </template>
            
            <template v-else-if="column.key === 'has_pdb'">
              <a-tag :color="record.has_pdb ? 'success' : 'default'">
                {{ record.has_pdb ? $t('sequenceSearch.table.hasStructure') : $t('sequenceSearch.table.noStructure') }}
              </a-tag>
            </template>
          </template>
        </a-table>
        
        <!-- 日志面板(可折叠) -->
        <a-collapse v-if="searchResults.logs" style="margin-top: 16px;">
          <a-collapse-panel key="logs" :header="`📋 ${$t('sequenceSearch.viewLogs')}`">
            <div 
              v-for="(log, idx) in searchResults.logs" 
              :key="idx" 
              style="font-family: monospace; font-size: 12px; padding: 4px 0; line-height: 1.8;"
            >
              <span :style="{ color: log.level === 'error' ? '#f5222d' : '#606266' }">
                [{{ formatLogTime(log.timestamp) }}] {{ log.message }}
              </span>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
    </a-layout-content>
  </a-layout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { 
  SearchOutlined, 
  ThunderboltOutlined,
  ExperimentOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  DatabaseOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import config from '../config/env'
import NavBar from '../components/NavBar.vue'

const { t } = useI18n()
const querySequence = ref('')
const evalue = ref(0.001)
const maxResults = ref(100)
const searching = ref(false)
const searchResults = ref(null)

const columns = computed(() => [
  { 
    title: t('sequenceSearch.table.accession'), 
    dataIndex: 'accession', 
    key: 'accession', 
    width: 150, 
    fixed: 'left' 
  },
  { 
    title: t('sequenceSearch.table.species'), 
    dataIndex: 'species', 
    key: 'species', 
    width: 200, 
    ellipsis: true 
  },
  { 
    title: t('sequenceSearch.table.type'), 
    dataIndex: 'type', 
    key: 'type', 
    width: 120 
  },
  { 
    title: t('sequenceSearch.table.identity'), 
    dataIndex: 'identity', 
    key: 'identity', 
    width: 180,
    sorter: (a, b) => a.identity - b.identity,
    defaultSortOrder: 'descend'
  },
  { 
    title: t('sequenceSearch.table.evalue'), 
    dataIndex: 'evalue', 
    key: 'evalue', 
    width: 120,
    sorter: (a, b) => a.evalue - b.evalue
  },
  { 
    title: t('sequenceSearch.table.bitScore'), 
    dataIndex: 'bit_score', 
    key: 'bit_score', 
    width: 100,
    sorter: (a, b) => a.bit_score - b.bit_score
  },
  { 
    title: t('sequenceSearch.table.alignmentLength'), 
    dataIndex: 'alignment_length', 
    key: 'alignment_length', 
    width: 100 
  },
  { 
    title: t('sequenceSearch.table.pdbStructure'), 
    dataIndex: 'has_pdb', 
    key: 'has_pdb', 
    width: 100, 
    align: 'center' 
  }
])

const searchSequence = async () => {
  if (!querySequence.value.trim()) {
    message.error(t('sequenceSearch.noInput'))
    return
  }
  
  searching.value = true
  searchResults.value = null
  
  try {
    const formData = new FormData()
    formData.append('sequence', querySequence.value)
    formData.append('evalue', evalue.value)
    formData.append('max_target_seqs', maxResults.value)
    
    const response = await axios.post(
      `${config.API_BASE_URL}/api/search/sequence/`,
      formData
    )
    
    searchResults.value = response.data
    
    if (response.data.total_hits === 0) {
      message.warning(t('sequenceSearch.noResults'))
    } else {
      const cached = response.data.cached ? `(${t('sequenceSearch.cached')})` : ''
      const time = response.data.execution_time 
        ? ` - ${response.data.execution_time.toFixed(3)}s` 
        : ''
      message.success(t('sequenceSearch.searchSuccess', { count: response.data.total_hits }) + cached + time)
    }
  } catch (error) {
    const detail = error.response?.data?.detail || error.message
    message.error(t('sequenceSearch.searchFailed') + ': ' + detail)
    console.error('Search error:', error)
  } finally {
    searching.value = false
  }
}

const clearForm = () => {
  querySequence.value = ''
  searchResults.value = null
  message.info(t('sequenceSearch.cleared'))
}

const loadExample = () => {
  querySequence.value = `>Example Protein
MTKLNTALIDRLIAAGGMVVKKQAPQPTRSWHDDPDDRDREVRQYEPDEVEYWYNYRIIFNGRTESLVGIDFYDLPSVRYDARYDCWSSDYSEHAPSVIAAVRARLQA`
  message.info(t('sequenceSearch.exampleLoaded'))
}

const getIdentityColor = (identity) => {
  if (identity >= 90) return '#52c41a'  // 绿色:高相似
  if (identity >= 70) return '#1890ff'  // 蓝色:中等相似
  if (identity >= 50) return '#faad14'  // 橙色:低相似
  return '#f5222d'  // 红色:很低相似
}

const formatLogTime = (timestamp) => {
  // 提取时间部分 (HH:MM:SS)
  if (!timestamp) return ''
  const time = timestamp.split('T')[1]?.split('.')[0]
  return time || timestamp
}
</script>

<style scoped>
:deep(.ant-btn-primary) {
  background: #409eff;
  border-color: #409eff;
}

:deep(.ant-btn-primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

:deep(.ant-statistic-title) {
  color: #606266;
  font-size: 14px;
}

:deep(.ant-statistic-content) {
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-progress-text) {
  font-size: 12px;
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #e4e7ed;
}

:deep(.ant-collapse) {
  background: #fafafa;
  border: 1px solid #e4e7ed;
}

:deep(.ant-collapse-header) {
  font-weight: 600;
  color: #2c3e50;
}
</style>
